package com.touchfired.common.core.listener.impl;

import com.touchfired.common.constants.ClientInfo;
import com.touchfired.common.constants.RoomInfo;
import com.touchfired.common.context.ServerContext;
import com.touchfired.common.core.callback.Callback;
import com.touchfired.common.core.event.impl.ChatEvent;
import com.touchfired.common.core.event.impl.RoomJoinEvent;
import com.touchfired.common.core.event.impl.RoomQuitEvent;
import com.touchfired.common.core.event.impl.SendRoomDetailEvent;
import com.touchfired.common.core.listener.BaseListener;
import com.touchfired.common.core.publisher.impl.EventPublisher;
import com.touchfired.common.params.RoomRespInfo;
import com.touchfired.common.utils.RoomUtil;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

/**
 * 退出房间 监听器
 *
 * @author 幸佳俊
 */
@Component
public class RoomJoinListener extends BaseListener<RoomJoinEvent> {

    private final ServerContext serverContext;
    private final EventPublisher publisher;
    public RoomJoinListener(ServerContext serverContext, EventPublisher publisher) {
        this.serverContext = serverContext;
        this.publisher = publisher;
    }

    @Override
    public void onEvent(RoomJoinEvent roomJoinEvent, Callback callback) {
        ClientInfo clientInfo = roomJoinEvent.getClientInfo();
        RoomInfo roomInfo = roomJoinEvent.getRoomInfo();

        clientInfo.setRoomId(roomInfo.getRoomId());
        roomInfo.getRoomClientLongIds().add(clientInfo.getLongId());
        serverContext.updateClientInfo(clientInfo);
        serverContext.updateRoomInfo(roomInfo);

        LinkedList<String> roomClientLongIds = roomInfo.getRoomClientLongIds();
        List<ClientInfo> roomClients = RoomUtil.getRoomClients(roomClientLongIds);
        publisher.publish(new ChatEvent(clientInfo, roomClients, "加入房间"));
        publisher.publish(new SendRoomDetailEvent(roomInfo));

        callback.call(RoomUtil.converter(roomInfo));
    }

}
